package com.api.zszsj2.util;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;

public class HTMLToImage {
    public static void html2Image(String html,String path,int width, int height) {
        if(width<=0)
            width = 300;
        if(height<=0)
            height = 400;
        //load the webpage into the editor
        //JEditorPane ed = new JEditorPane(new URL("http://www.google.com"));
        JEditorPane jep = new JEditorPane("text/html",null);
        Font font = new Font("Microsoft YaHei", Font.PLAIN, 12);
        //Microsoft YaHei : 微软雅黑
        //SimSun : 宋体
        //SimHei : 黑体
        //KaiTi : 楷体
        //YouYuan : 幼圆
        //FangSong : 仿宋
        //FangSong_GB2312 : 仿宋_GB2312
        jep.setFont(font);

        jep.setSize(width, height);

        jep.setEditable(false);
        CustomHTMLEditorKit toolKit = new CustomHTMLEditorKit();
        jep.setEditorKit(toolKit);
        jep.setText(html);
        Dimension size = jep.getSize();
//        int ww = size.width;
//        int hh = size.height;
//        jep.resize(ww,hh);
        //create a new image
//        BufferedImage image = new BufferedImage(jep.getWidth(), jep.getHeight(),BufferedImage.TYPE_INT_ARGB);
        BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_ARGB);

        //paint the editor onto the image
        SwingUtilities.paintComponent(image.createGraphics(),
                jep,
                new JPanel(),
                0, 0, image.getWidth(), image.getHeight());
        //save the image to file
        try {
            ImageIO.write((RenderedImage) image, "png", new File(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}